<template>
  <div class="form" style="padding: 20px">
    <el-form
      class="zyp"
      :model="formData"
      ref="formRef"
      :inline="true"
      label-width="120px"
      @submit.native.prevent
    >
      <el-row>
        <template v-for="item in options">
          <slot :name="item.prop" :formData="formData" :option="item">
            <el-col :span="8">
              <el-form-item
                :key="item.prop"
                :label="item.label"
                :prop="item.prop"
                :required="item.required"
              >
                <el-input
                  v-if="item.type == 'input'"
                  @change="changeInput(item, $event)"
                  type="text"
                  style="width: 100%"
                  v-model="formData[item.prop]"
                  :placeholder="placeholders[item.type] + item.label"
                />
                <el-select
                  style="width: 100%"
                  v-else-if="item.type == 'select'"
                  v-model="formData[item.prop]"
                >
                  <el-option
                    v-for="ele in item.optionItems"
                    :label="ele.text"
                    :value="ele.value"
                  >
                  </el-option>
                </el-select>
                <el-select
                  style="width: 100%"
                  v-else-if="item.type == 'zyry'"
                  v-model="formData[item.prop]"
                  multiple
                  filterable
                  allow-create
                  @change="changeZyry(item, $event)"
                >
                  <el-option
                    v-for="ele in selectZyry"
                    :label="ele"
                    :value="ele"
                  >
                  </el-option>
                </el-select>

                <!-- 其他安全措施 -->
                <el-select
                  style="width: 100%"
                  v-else-if="item.type == 'qtaqcs'"
                  v-model="formData[item.prop]"
                  multiple
                  filterable
                  allow-create
                  @change="changeZyry(item, $event)"
                >
                  <el-option
                    v-for="ele in qtaqcsItems"
                    :label="ele"
                    :value="ele"
                  >
                  </el-option>
                </el-select>

                <el-select
                  style="width: 100%"
                  v-else-if="item.type == 'glzyp'"
                  v-model="formData[item.prop]"
                  multiple
                >
                  <el-option
                    v-for="ele in zypList"
                    :label="ele.text"
                    :value="ele.value"
                  >
                  </el-option>
                </el-select>
                <el-select
                  style="width: 100%"
                  v-else-if="item.type == 'zsbh'"
                  v-model="formData[item.prop]"
                  multiple
                >
                  <el-option
                    v-for="ele in zyzsList"
                    :label="ele.text"
                    :value="ele.value"
                  >
                  </el-option>
                </el-select>
                <el-select
                  style="width: 100%"
                  v-else-if="item.type == 'mselect'"
                  v-model="formData[item.prop]"
                  multiple
                >
                  <el-option
                    v-for="ele in item.optionItems"
                    :label="ele.text"
                    :value="ele.value"
                  >
                  </el-option>
                </el-select>
                <el-select
                  style="width: 100%"
                  v-else-if="item.type == 'combox'"
                  v-model="formData[item.prop]"
                  multiple
                  filterable
                  allow-create
                >
                  <el-option
                    v-for="ele in item.optionItems"
                    :label="ele"
                    :value="ele"
                  >
                  </el-option>
                </el-select>

                <el-date-picker
                  v-else-if="
                    ['datetime', 'datetimerange', 'daterange'].includes(
                      item.type
                    )
                  "
                  style="width: 100%"
                  :type="item.type"
                  v-model="formData[item.prop]"
                  format="YYYY年MM月DD日 HH时mm分"
                  value-format="YYYY-MM-DD HH:mm"
                  @change="change(item.prop, $event, item.type)"
                  :placeholder="placeholders[item.type] + item.label"
                  :hide-second="true"
                />

                <!-- 自动计算结束时间组件 -->
                <div
                  v-else-if="['newdatetimerange'].includes(item.type)"
                  style="display: flex"
                >
                  <el-date-picker
                    type="datetime"
                    style="width: 100%"
                    v-model="formData[item.prop][0]"
                    format="YYYY年MM月DD日 HH时mm分"
                    value-format="YYYY-MM-DD HH:mm"
                    @change="changeJobTime(item.prop, $event, item.type)"
                    placeholder="请选择开始时间"
                    :disabled="jobType == 2 && !formData.dhzyjb"
                  />
                  <el-date-picker
                    style="width: 100%"
                    v-model="formData[item.prop][1]"
                    type="datetime"
                    format="YYYY年MM月DD日 HH时mm分"
                    value-format="YYYY-MM-DD HH:mm"
                    :disabled="jobType == 2 && !formData.dhzyjb"
                  ></el-date-picker>
                </div>
                <!-- <el-radio-group
                    style="width: 100%"
                    v-else-if="item.type == 'radio'"
                    v-model="formData[item.prop]"
                  >
                    <el-radio
                      :label="ele.value"
                      v-for="ele in item.optionItems"
                    >
                      {{ ele.text }}</el-radio
                    >
                  </el-radio-group> -->

                <el-select
                  style="width: 100%"
                  v-else-if="item.type == 'checkbox'"
                  v-model="formData[item.prop]"
                  multiple
                >
                  <el-option
                    v-for="ele in item.optionItems"
                    :label="ele.text"
                    :value="ele.value"
                  >
                  </el-option>
                </el-select>
                <el-select
                  style="width: 100%"
                  v-else-if="item.type == 'radio'"
                  v-model="formData[item.prop]"
                >
                  <el-option
                    v-for="ele in item.optionItems"
                    :label="ele.text"
                    :value="ele.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </slot>
        </template>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { onMounted, ref, defineProps, defineEmits, watch, nextTick } from "vue";
import { formatDate2 } from "@/utils/index.js";
import { apis } from "@/api/zygl/zyp";

const placeholders = {
  datetime: "请选择",
  date: "请选择",
  datetimerange: "请选择",
  daterange: "请选择",
  select: "请选择",
  input: "请输入",
  zyry: "请选择",
};
const emits = defineEmits(["onChange", "onSubmit"]);
const props = defineProps({
  rules: {
    type: Object,
    default: () => ({}),
  },
  formOption: {
    type: Array,
    default: () => [],
  },
  zyryList: {
    type: Array,
    default: () => [],
  },
  zypList: {
    type: Array,
    default: () => [],
  },
  jobType: [String, Number],
});

const submitForm = async () => {
  const res = await getFormData();
  if (res) {
    formatTimes();
    emits("onSubmit", { ...keepData.value, ...formData.value });
    return { ...keepData.value, ...formData.value };
  } else {
    uni.showModal({
      title: "有必填项未填",
    });
    return false;
  }
};
const options = ref([]);
const formData = ref({});
const keepData = ref({});
function setFormData(data = {}) {
  keepData.value = JSON.parse(JSON.stringify(data));
  formData.value = { ...data };
}
function setOptions(option) {
  if (option) {
    options.value = JSON.parse(JSON.stringify(option));
  } else {
    options.value = [];
  }
}
const formRef = ref();
async function getFormData() {
  try {
    const res = await formRef.value.validate();
    return { ...keepData.value, ...formData.value };
  } catch (e) {
    console.log(e);
    return false;
  }
}
const workTime = ref({
  5: 360,
  3: 168,
  10: 24,
});
// 自动计算时间
const workTimeFire = ref({
  "特级（8H）": 8,
  "一级（8H）": 8,
  "二级（72H）": 72,
});
const changeJobTime = (prop, value, type) => {
  nextTick(() => {
    if (prop == "jobDate" && props.jobType == 2) {
      let beginTime = getDateFromString(value);
      formData.value[prop][1] = formatDate2(
        beginTime.setHours(
          beginTime.getHours() + workTimeFire.value[formData.value.dhzyjb]
        )
      );
    } else if (prop == "jobDate" && workTime.value[props.jobType]) {
      let beginTime = getDateFromString(value);
      formData.value[prop][1] = formatDate2(
        beginTime.setHours(beginTime.getHours() + workTime.value[props.jobType])
      );
    }
  });
};
function getDateFromString(str) {
  var reg = /^(\d+)-(\d+)-(\d+) (\d+):(\d+)/;
  var s = str.match(reg);
  var result = "";
  if (s) {
    result = new Date(s[1], s[2] - 1, s[3], s[4], s[5]);
  }
  return result;
}

const change = (key, value) => {
  emits("onChange", {
    key,
    value,
  });
};

defineExpose({
  setFormData,
  setOptions,
  getFormData,
  submitForm,
});
const selectZyry = ref([]);
const zyzsbh = ref({});

watch(
  () => props.zyryList,
  () => {
    apis
      .getZyZsList({
        ids: props.zyryList
          .filter((ele) => ele.type == "out")
          .map((item) => item.id),
      })
      .then((res) => {
        zyzsbh.value = res.data;
      });
    selectZyry.value = props.zyryList.map((item) => item.label || item.name);
  }
);

const qtaqcsItems = ref([
  '安全帽','防静电工作服','劳保鞋','绝缘鞋(靴)','防护手套','绝缘焊接手套','绝缘手套','焊接面具','面罩','护目镜','防尘毒口罩','耳塞','安全带','四合一气体检测仪','照明用具','通讯设备','其他防护'
])

const changeInput = (op, value) => {
  if (!op.hz || value.includes(op.hz)) {
    return;
  } else {
    formData.value[op.prop] = value + op.hz;
  }
};
const formatTimes = () => {
  options.value.forEach((item) => {
    if (item.type.includes("time")) {
      let value = formData.value[item.prop];
      if (item.type.includes("range")) {
        value = formData.value[item.prop] || [];
        let values = [];
        if (value.length == 0) return;
        value.forEach((ele, index) => {
          if (ele.length < 12) {
            values[index] = ele + "00:00";
          } else {
            values[index] = ele;
          }
        });
        formData.value[item.prop] = values;
      } else {
        if (!value) return;
        formData.value[item.prop] = value.length < 12 ? value + "00:00" : value;
      }
    }
  });
};
const zyzsList = ref([]);

// 选择作业人员 自动带出票证号
const changeZyry = (option, val) => {
  if (option.bh) {
    const zsbh = props.zyryList.filter((item) => val.includes(item.name));
    let selectedList = [];
    zsbh.forEach((item) => {
      const list = zyzsbh.value[item.id];
      if (list && list.length) {
        list.forEach((ele) => {
          selectedList.push({
            text:
              item.name + "-" + ele.certificateName + "-" + ele.certificateCode,
            value: ele.certificateCode,
            id: ele.id,
          });
        });
      }
    });
    zyzsList.value = selectedList;
  }
};
</script>

<style lang="scss" scoped>
.page {
  background-color: #fff !important;
}
.is-input-border {
  border: none !important;
}

.checklist-group {
  padding: 10px;
}
.submit {
  position: fixed;
  bottom: 0;
  height: 12vw;
  width: 100vw;
}
</style>
